import BLELocker from '../BLELocker.js';
import CONSTANT_DATA from '../util.js';
var util = require("util.js");
var retryGetServiceCount = 2;
var app = getApp();
const SERVICE_FEE7_UUID = "0000FEE7-0000-1000-8000-00805F9B34FB";
const CHARACTERIS_FEC7_UUID = "0000FEC7-0000-1000-8000-00805F9B34FB";
const CHARACTERIS_FEC8_UUID = "0000FEC8-0000-1000-8000-00805F9B34FB";

function connectLease(device, scanMac, scanMacCallback) { 
  if (app.globalData._that){
    wx.showLoading({
      title: '连接...',
    })
  }

  let conTimeoutLen = app.globalData.conRetryTotalCount == app.globalData.conRetryCount ? 5000 : 10000;
  wx.createBLEConnection({
    deviceId: device.deviceId,
    timeout: conTimeoutLen,
    success:function(res){
      app.globalData.conNoticeTimer = setTimeout(function(){
        if (!app.globalData.conIsSuc) {
          if (app.globalData.conTimeoutTimer) {
            clearTimeout(app.globalData.conTimeoutTimer);
          }
          wx.showModal({
            title: '提示',
            showCancel:false,
            content: '设备响应超时,请重新扫码',
            success (res) {
            }
          })
          wx.closeBLEConnection({
            deviceId: device.deviceId,
            success: function (res) {
              console.log("连接关闭成功,", scanMac, res);
            },
            fail: function (err) {
              console.log("关闭失败,", scanMac, err);
            }
          })
        }
      },10000);
      app.globalData.beforeConIsGateway = false;

      wx.showLoading({
        title: '读数据...',
      })
      cacheScanMac(scanMac, device.deviceId);
      app.globalData.conRetryCount = -1;
      BLELocker.setDevice(device);
      //停止搜索
      wx.stopBluetoothDevicesDiscovery({
        success(res) {
          console.log(res)
        }
      })

      getSerciceAndNotify(device, 50);

    },
    fail:function(err){
      //停止搜索
      wx.stopBluetoothDevicesDiscovery({
        success(res) {
          console.log(res)
        }
      })

      if (scanMac) {
        //移除掉缓存
        let delMac = scanMac.indexOf("DK") == 0 ? scanMac.substring(2) : scanMac;
        wx.removeStorageSync(delMac);
      }
      console.log("连接失败:" + app.globalData.conRetryCount, err);
      let errInfo = err ? JSON.stringify(err) : "";
      let devId = device ? device.deviceId : "null";
      util.recordLog(CONSTANT_DATA.err_type.new_con_fail, "连接失败" + app.globalData.conRetryCount + ":" + scanMac + ":" + errInfo + ":" + devId);
      if (app.globalData.conTimeoutTimer) {
        clearTimeout(app.globalData.conTimeoutTimer);
        app.globalData.conTimeoutTimer = setTimeout(function () {
          if (!app.globalData.conIsSuc) {            
            wx.showModal({
              title: '提示',
              showCancel:false,
              content: '连接超时，请关闭蓝牙再打开后重试',
              success (res) {
              }
            })
            wx.closeBLEConnection({
              deviceId: device.deviceId,
              success: function (res) {
                console.log("连接关闭成功,", scanMac, res);
              },
              fail: function (err) {
                console.log("关闭失败,", scanMac, err);
              }
            })
          }
        }, 35000);
      }

    }
  })
}

function getSerciceAndNotify(device,serviceTimeoutLen) {
  setTimeout(function () {
    wx.getBLEDeviceServices({
      deviceId: device.deviceId,
      success:function(res) {        
        console.log("应用服务接口。。", res);
        //获取1530的服务
        for (var i = 0; i < res.services.length; i++) {
          var uuid = res.services[i]["uuid"]
          if (uuid.indexOf("0000FEE7") != -1) {
            console.log("应用服务uuid-->" + uuid);
            device.fee7 = res.services[i];
          }
        }
        if (!device.fee7) {
          //使用固定的值进行处理
          console.log("没有获取到服务uuid采用固定值:"+SERVICE_FEE7_UUID);
          util.recordLog(CONSTANT_DATA.err_type.new_conf_uuid_nofound, "用固定服务uuid:" + SERVICE_FEE7_UUID + ":" + app.globalData.isLeaseCon);
          device.fee7 = {uuid:SERVICE_FEE7_UUID,isPrimary:true};
        }
        //获取特征码值并发起通知
        getCharacteristics(device);    
      },
      fail:function(err){
        console.log("获取getBLEDeviceServices失败:" + retryGetServiceCount, err);
        util.recordLog(CONSTANT_DATA.err_type.new_conf_service_fail, "用固定的服务uuid:" + retryGetServiceCount + ":" + app.globalData.isLeaseCon);
        if (app.globalData.conNoticeTimer) {
          clearTimeout(app.globalData.conNoticeTimer);
        }

        device.fee7 = { uuid: SERVICE_FEE7_UUID, isPrimary: true };
        //采用固定值进行获取特征码值
        getCharacteristics(device);    
        
      }
    })
  }, serviceTimeoutLen);
}

function getCharacteristics(device){
  setTimeout(function () {
    wx.getBLEDeviceCharacteristics({
      deviceId: device.deviceId,
      serviceId: device.fee7["uuid"],
      success: function (res) {
        console.log("获取特征码...", res);
        for (var i in res.characteristics) {
          var c = res.characteristics[i]
          if (c.uuid.indexOf("FEC7") != -1 || c.uuid ==  "000036F5-0000-1000-8000-00805F9B34FB") {
            device.fec7 = c
            BLELocker.setWriteUuid(c.uuid, device.fee7["uuid"]);
          }
          if (c.uuid.indexOf("FEC8") != -1 || c.uuid ==  "000036F6-0000-1000-8000-00805F9B34FB") {
            device.fec8 = c
          }
        }
        if (!device.fec7) {
          device.fec7 = {uuid:CHARACTERIS_FEC7_UUID};
        }
        if (!device.fec8) {
          device.fec8 = {uuid:CHARACTERIS_FEC8_UUID};
        }
        //发起通知后可以立刻接收到蓝牙返回的数据
        wx.notifyBLECharacteristicValueChange({
          deviceId: device.deviceId,
          serviceId: device.fee7["uuid"],
          characteristicId: device.fec8["uuid"],
          state: true,
          success: function (res) {
            console.log("发送通知成功...", res);
            callback(device);

            if (app.globalData.conNoticeTimer) {
              clearTimeout(app.globalData.conNoticeTimer);
            }
          },
          fail:function(err){

          },
          complete:function(res) {
            if(device.fec7 && device.fec7.uuid == "000036F5-0000-1000-8000-00805F9B34FB") {              
                console.log("陪护椅发送获取token")
                setTimeout(function () {
                  bleGetToken();
                }, 1200);
            }
          }
        })
      },
      fail: function (err) {
        console.log("获取特征码失败", err);
        let errInfo = err ? JSON.stringify(err) : "null";
        util.recordLog(CONSTANT_DATA.err_type.new_conf_char_fail, "获取特征码失败:" + errInfo + ":" + app.globalData.isLeaseCon);
        if (app.globalData.conNoticeTimer) {
          clearTimeout(app.globalData.conNoticeTimer);
        }
        if (app.globalData.conTimeoutTimer) {
          clearTimeout(app.globalData.conTimeoutTimer);
        }
        //发起通知后可以立刻接收到蓝牙返回的数据
        wx.notifyBLECharacteristicValueChange({
          deviceId: device.deviceId,
          serviceId: CHARACTERIS_FEC7_UUID,
          characteristicId: CHARACTERIS_FEC8_UUID,
          state: true,
          success: function (res) {
            console.log("发送通知成功...", res);
            callback(device);

            if (app.globalData.conNoticeTimer) {
              clearTimeout(app.globalData.conNoticeTimer);
            }
          },
          fail: function (err) {
            //关闭连接，关闭适配器
            console.log("发送通知失败...", err);
            wx.closeBLEConnection({
              deviceId: device.deviceId,
              success: function (res) {
              },
              complete: function () {
                wx.closeBluetoothAdapter({
                  success: function (res) { },
                })
              }
            })
            if (!app.globalData.conIsSuc && app.globalData._that) {
              wx.showModal({
                title: '提示',
                showCancel:false,
                content: '获取特征码失败,请重新扫码',
                success (res) {
                }
              })
            } else {
              wx.showModal({
                title: '温馨提示',
                content: '获取特征码失败,请重新扫码(Z' + app.globalData.curConHid + ')'
              })
            }
          }
        })
      }
    })
  }, 50)
}

//收到固件传来的信息处理，开启notify后，向1531写入信息后，固件会传回信息
function callback(device) {
  BLELocker.statusChanged(BLELocker.Status.bleReceiveData);  
  wx.onBLECharacteristicValueChange(function (res) {
    let hexValue = util.hexFromBuffer(res.value).toUpperCase();//将信息转为16进制
    console.log("返回的数据:" + hexValue);
    BLELocker.handleDeviceData(hexValue.toUpperCase(), device,res);   
  })
}  

//缓存
function cacheScanMac(mac, deviceId) {
  if (mac && mac.indexOf("DK") == 0) {
    let sMac = mac.substring(2);
    let device = { "deviceId": deviceId };
    wx.setStorageSync(sMac, device);
  }
}

/**
 * 获取陪护椅的token
 */
function bleGetToken() {
  console.log("bleGetToken");
  for (var e = app, a = 0; a < e.globalData.bleVariable.cmds.getTokenCmd.length; a++) a <= 3 || (e.globalData.bleVariable.cmds.getTokenCmd[a] = Math.round(100 * Math.random()));
  BLELocker.sendPeiHuYiBleGetToken(
    function(isSuccess) {
      if (isSuccess == false) {
        util.recordLog(CONSTANT_DATA.err_type.data_peihuyi_token_send_fail,  "陪护椅token发送失败")        
      } else {
        util.recordLog(CONSTANT_DATA.err_type.data_peihuyi_token_send_suc, "陪护椅token发送成功")
      }
    }
  );
}


module.exports = {
  connectLease: connectLease,
  getSerciceAndNotify: getSerciceAndNotify
}